import './index.scss';

import { Button, Card, Form, Input, Modal, Popconfirm, SelectProps } from 'antd';
import { FC } from 'react';

import CloseIcon from '@/assets/icons/close.svg';
import EditIcon from '@/assets/icons/edit.svg';
import PlusIcon from '@/assets/icons/plus.svg';
import { EnumEditor } from '@/components/base/TagEditor';
import { VariableTypeSelector, VariableValueField } from '@/components/base/ValueOfType';
import { colors } from '@/config/theme';
import { booleanOptions } from '@/constants/config';
import { useCurrentNode } from '@/hooks/useCurrentNode';
import { useMode } from '@/store/mode';

import { VariablesTable } from '../VariablesTable';

interface NodeVariableMangerFormProps {
  edges?: boolean;
  /** 私有变量  通用变量 */
  type?: 'private' | 'public';
  /** 标题 */
  title?: string;
}

export const NodeVariableMangerForm: FC<NodeVariableMangerFormProps> = memo((props) => {
  const [variableDialogVisible, setVariableDialogVisible] = useState(false);
  const { mode } = useMode();
  const [formRef] = Form.useForm();
  const { setPrivateVariables, privateVariables, publicVariables, setPublicVariables } = useCurrentNode();
  let modifyIndex = useRef(-1);
  const [varType, setVarType] = useState<any>('');
  const [options, setOptions] = useState<SelectProps['options']>([]);

  const variables = useMemo(() => {
    return (props.type !== 'public' ? privateVariables : publicVariables) || [];
  }, [privateVariables, props.type, publicVariables]);

  const setVariables = useMemo(() => {
    return props.type !== 'public' ? setPrivateVariables : setPublicVariables;
  }, [setPrivateVariables, props.type, setPublicVariables]);

  const title = props.title || '私有变量';

  const onConfirm = () => {
    formRef?.validateFields().then((vars) => {
      let options = vars.options;
      if (vars.varType === 'BOOLEAN') {
        options = booleanOptions;
      } else {
        if (vars.varType !== 'ENUM') {
          options = [];
        }
      }
      // 新增
      if (modifyIndex.current === -1) {
        setVariables([...variables, { ...vars, options }]);
      } else {
        setVariables([
          ...variables.slice(0, modifyIndex.current),
          { ...vars!, options },
          ...variables.slice(modifyIndex.current + 1)
        ]);
      }
      closeModal();
      formRef?.resetFields();
    });
  };

  const closeModal = () => {
    setVarType('');
    setOptions([]);
    setVariableDialogVisible(false);
  };

  const varNameValidator = (rule: any, value: string, callback: any) => {
    if (!value) {
      return callback(new Error('请输入变量名称'));
    }
    if (variables.some((item, index) => item.varName === value && index !== modifyIndex.current)) {
      return callback(new Error('变量名称重复, 请更换其他名称'));
    }
    callback();
  };

  const canAddVariable = !props.edges && mode === 'edit';

  return (
    <div onClick={(e) => e.stopPropagation()} className="flex flex-col">
      <div className="operation-left flex flex-col">
        <Card
          size="small"
          title={title}
          extra={
            canAddVariable ? (
              <Button
                size="middle"
                type="text"
                onClick={() => {
                  modifyIndex.current = -1;
                  setVariableDialogVisible(true);
                }}>
                <PlusIcon color={colors.gray[500]} width={18} height={18} name="plus" />
                <span className="text-value-14 pr-12">添加变量</span>
              </Button>
            ) : null
          }>
          {variables.length > 0 ? (
            <div className="var-list">
              <VariablesTable
                actions={{
                  title: <div className="text-center">操作</div>,
                  key: 'action',
                  width: 190,
                  render: (text: any, record: any, index: number) => (
                    <div className="var-item__action flex gap-8 justify-center" onClick={(e) => e.stopPropagation()}>
                      <EditIcon
                        onClick={() => {
                          setVarType(record.varType);
                          setOptions(record.options || []);
                          setVariableDialogVisible(true);
                          modifyIndex.current = index;
                          formRef?.setFieldsValue({ ...record });
                        }}
                        width={18}
                        height={18}
                        className="cursor-pointer"
                        name="edit"
                      />
                      <Popconfirm
                        onConfirm={() => {
                          variables.splice(index, 1);
                          setVariables([...variables]);
                        }}
                        confirm-button-text="确定"
                        cancel-button-text="取消"
                        title="确定删除?">
                        <span>
                          <CloseIcon width={18} height={18} className="cursor-pointer" />
                        </span>
                      </Popconfirm>
                    </div>
                  )
                }}
                dataSource={variables}
              />
            </div>
          ) : <div className='text-14 text-center'>暂无变量</div>}
        </Card>
      </div>

      <Modal
        width={540}
        destroyOnClose
        title={modifyIndex.current === -1 ? '添加变量' : '编辑变量'}
        onCancel={() => {
          closeModal();
          formRef?.resetFields();
        }}
        modalRender={(dom) => {
          return (
            <Form
              form={formRef}
              onValuesChange={(value) => {
                if ('varType' in value) {
                  setVarType(value.varType);
                }
                if ('options' in value) {
                  setOptions(value.options);
                }
              }}
              layout="vertical">
              {dom}
            </Form>
          );
        }}
        onOk={onConfirm}
        open={variableDialogVisible}>
        <div className="flex justify-between gap-20">
          <Form.Item
            className="flex-1"
            required
            label="变量名称"
            name="varName"
            rules={[
              {
                validator: varNameValidator,
                validateTrigger: ['change', 'blur']
              }
            ]}>
            <Input placeholder="请输入变量名称" />
          </Form.Item>
          <Form.Item className="flex-1" required label="变量中文名" name="varLabel">
            <Input placeholder="请输入变量中文名" />
          </Form.Item>
        </div>
        <Form.Item className="flex-1" required label="变量类型" name="varType">
          <VariableTypeSelector />
        </Form.Item>
        {varType === 'ENUM' && (
          <Form.Item name="options" className="flex-1" required label="枚举列表">
            <EnumEditor />
          </Form.Item>
        )}
        {varType && (
          <Form.Item dependencies={['varType', 'options']} label="变量默认值" name="initValue">
            <VariableValueField varType={varType!} options={options} />
          </Form.Item>
        )}
      </Modal>
    </div>
  );
});
